import {Form, message, Radio} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {CashManager} from "@/services/api-functions";
import {SYS_ENUMS} from "@/utils/constants";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {ModalForm, ProFormSelect, ProFormTextArea} from "@ant-design/pro-form";


export const cashAudit = async (fields: any, select: any) => {
  if (!select) return false;
  try {
    if (isSuccess((await CashManager.audit({
      businessId: select.id,
      auditOperate: fields.auditOperate,
      remark: fields.remark,
      flowType: 'CASH_AUDIT',
    }))?.code)) {
      message.success(fields.auditOperate === SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value ? '审核通过' : '审核拒绝');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};


const CashList: React.FC<any> = ({}) => {
  const [auditFormRef] = Form.useForm()
  const [auditState, setAuditState] = useState<'ALL' | 'CASHING' | 'FINISH' | 'REFUSE'>('CASHING');
  const [countInfo, setCountInfo] = useState<{ ALL: number, CASHING: number, FINISH: number, REFUSE: number }>({
    ALL: 0,
    CASHING: 0,
    FINISH: 0,
    REFUSE: 0,
  });
  const [auditVisible, handleAuditVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const columns: ProColumns[] = [
    {
      title: '用户',
      dataIndex: ['userDto', 'nickName'],
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 150,
      hideInForm: true,
    },
    {
      title: '用户名',
      dataIndex: 'nickName',
      ellipsis: true,
      hideInTable: true,
      width: 120,
    },
    {
      title: '姓名',
      dataIndex: 'realName',
      ellipsis: true,
      width: 120,
    },
    {
      title: '提现方式',
      dataIndex: 'cashChannel',
      valueEnum: SYS_ENUMS.CASH_CHANNEL,
      ellipsis: true,
      width: 100,
    },
    {
      title: '打款账户',
      dataIndex: 'account',
      width: 200,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '开户行',
      dataIndex: 'bankOpen',
      width: 170,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '提现金额',
      dataIndex: 'cashAmount',
      width: 130,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '提现状态',
      dataIndex: 'cashStatus',
      valueEnum: SYS_ENUMS.CASH_STATUS,
      ellipsis: true,
      width: 100,
      hideInSearch: true,
    },
    {
      title: '打款时间',
      dataIndex: 'finishTime',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '申请时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '申请时间',
      dataIndex: 'gmtCreateTimeRange',
      valueType: 'dateTimeRange',
      width: 170,
      hideInTable: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      fixed: 'right',
      hideInForm: true,
      render: (_, record) => [
        record.cashStatus === 'CASHING'
          ? <a key="edit" onClick={() => {
            setCurrentRow(record)
            auditFormRef?.resetFields()
            handleAuditVisible(true)
          }}>审核</a> : <span style={{color: 'gray'}}>审核</span>
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any, any>
        headerTitle={<Radio.Group value={auditState} onChange={(e) => {
          setAuditState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.ALL ?? 0}</Radio.Button>
          <Radio.Button value='CASHING'>待审核 {countInfo?.CASHING ?? 0}</Radio.Button>
          <Radio.Button value='FINISH'>已打款 {countInfo?.FINISH ?? 0}</Radio.Button>
          <Radio.Button value='REFUSE'>已拒绝 {countInfo?.REFUSE ?? 0}</Radio.Button>
        </Radio.Group>}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        request={async (params) => {

          const query = {...params}
          if (auditState !== 'ALL') {
            query.cashStatus = auditState
          }

          if (params.gmtCreateTimeRange) {
            query.startTime = params.gmtCreateTimeRange[0]
            query.endTime = params.gmtCreateTimeRange[1]
            delete query.gmtCreateTimeRange
          }
          const {data: {data, total}, code}: any = await CashManager.list(query);

          const res = await CashManager.cashCountInfo();

          if (isSuccess(res.code)) {
            setCountInfo(res.data)
          }

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{x: 1300}}
      />

      <ModalForm
        title={`审核【${currentRow?.title}】`}
        width="750px"
        form={auditFormRef}
        visible={auditVisible}
        onVisibleChange={v => {
          handleAuditVisible(v)
          if (!v) {
            auditFormRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await cashAudit(value as any, currentRow)) {
            handleAuditVisible(false);
            auditFormRef?.resetFields()
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect label='审核结果' required rules={[{required: true, message: '请填选择审核结果',},]} name='auditOperate'
                       initialValue={SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value} options={[
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value},
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.value},
        ]}/>
        <ProFormTextArea label='备注' name="remark"/>
      </ModalForm>
    </PageContainer>
  );
};

export default CashList;
